// routers.js

var sanitize = require('validator').sanitize;
var check = require('validator').check;
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
function htmlEntities(str){
  return String(str).replace(/</g, '').replace(/>/g, '').replace(/http:\/\//, '').replace(/https:\/\//,'');
}
function htmlBook(str){
	return String(str).replace(/《/g, '').replace(/》/g,'').replace(/</g, '').replace(/>/g, '');
}
var ContentSchema = new Schema({
    stem: {type:String, default:'缺'},
    author: {type:String, default:'缺'},
    content: String,
    rand:{type:Number, default:Math.random() , index: true},
    created:{type:Date, default:Date.now()},
    ip: String,
    like: {type:Number, default:0},
    lastUpdate:{type:Date,default:Date.now()}
});
var sites = new Schema({
    name: {type:String, required:true},
    url: {type:String, required:true},
    summary: String,
    Visits: {type:Number, default:0},
    like: {type:Number, default:0},
    sorted: {type:Number, default:99}
});
var Bookmark = new Schema({
    classify: String,
    sites: [sites],
    created:{type:Date, default:Date.now()},
    sorted: {type:Number, default:99}
});
var Annotate = mongoose.model('Annotate', ContentSchema);
var BookMark = mongoose.model('Bookmark', Bookmark);

module.exports = function(app) {
	app.get('/', function(req, res) {
		res.send('部署完善中');
	});
	app.get('/pretty', function(req, res) {
		// res.send("hello world");
		Annotate.find({}, null, {sort: {'_id': -1}, limit: 5}, function(err, doc){
			if(err) console.log(err);
			res.render('addnote',{title:'hello',items:doc});
		});
	});	
	app.get('/bookmark', function(req, res) {
		BookMark.find({},null,{sort:{'sorted':1,'_id':1}}, function(err, doc){
			// doc.sites.sort({'sorted':1});33333333
			res.render('bookmark', {title:'bookmark',data: doc});
		});
	});
	app.post('/excerpt', function(req, res) {

	});
	app.post('/addnote', function(req, res) {
		// var stem = htmlEntities(req.body.stem);
		var stem = sanitize(req.body.stem).trim();
		stem = htmlBook(stem);
		stem = sanitize(stem).xss();
		var author = sanitize(req.body.author).trim();
		author = sanitize(author).xss();
		var content = sanitize(req.body.content).trim();
		content = sanitize(content).xss();
		if(content != ''&& stem != '') {
			var notes = Annotate();
			notes.content = content;
			notes.stem = stem;
			if(author != ''){
				notes.author = author
			}
			notes.save(function(err) {
				if(err) res.send({type:'err',msg:'出现错误'});
				res.send({type:'suc'});
			});
		} else {
			res.send({type:'err',msg:'摘句和句源不能为空'});
		}
	})
	app.post('/addmark', function(req, res) {
		var siteurl = htmlEntities(req.body.siteurl);
		siteurl = sanitize(siteurl).trim();
		siteurl = sanitize(siteurl).xss();
		var sitename = sanitize(req.body.sitename).trim();
		sitename = sanitize(sitename).xss();
		var sitesum = sanitize(req.body.sitesum).trim();
		sitesum = sanitize(sitesum).trim();
		if(req.body.siteid){
			console.log("hiyo siteid");
			var siteid = sanitize(req.body.siteid).trim();
			siteid = sanitize(siteid).trim();
			var date = {
				$set:{
					'sites.$.name': sitename,
					'sites.$.siteurl': siteurl,
					'sites.$.summary': sitesum
				}
			}
			BookMark.update({'sites._id':siteid}, date, function(err, doc){
				var sitesort = sanitize(req.body.sitesort).trim();
				sitesort = sanitize(sitesort).xss();
				if(err) res.send({type:'err',msg:'has err'});
				if(doc){
					// console.log(doc);
					res.send({type:'editsuc',msg:'编辑成功'});
					// doc.sites.id(id)
				} else {
					BookMark.update({'_id': siteid},{$set:{'classify':sitename,'sorted':sitesort}}, function(err, doc){
						if(err) res.send({type:'err',msg:'has err'});
						if(doc) res.send({type:'editsuc',msg:'classify编辑成功'});
					});
				}
			});
			return;
		}
		// BookMark.update({'sites._id':visit},{$inc:{'sites.$.Visits':1}},function(err, doc){
		if(siteurl != '' && sitename != ''){
			BookMark.findOne({_id:req.body.classify}, function(err, doc){
				if(err) return res.send({type:'err',msg:'无此节点'});
				doc.sites.push({name:sitename,url:siteurl,summary:sitesum});
				doc.save(function(err){
					if(err) return res.send({type:'err',msg:'添加失败'});
					res.send({type:'addsuc',msg:'添加成功'});
				});
			});
		} else {
			return res.send({type:'err', msg:'站名和网站地址不得为空'});
		}
	});
	app.get('/addclass/:classname', function(req, res){
		var classify = sanitize(req.params.classname).trim();
		classify = sanitize(classify).xss();
		if(classify != ''){
			BookMark.findOne({classify:classify}, function(err, doc){
				if(err) return res.redirect('/');
				if(!doc){
					BookMark.create({classify:classify},function(err, doc){
						if(err) return res.send(err);
						return res.send("添加成功<a href='/bookmark'>返回书签</a>");
					});
				} else {
					res.send("已经存在了哟<a href='/bookmark'>返回书签</a>");
				}
			});
		}
	});
	app.get('/Visits/:visit', function(req, res) {
		var visit = sanitize(req.params.visit).trim();
		visit = sanitize(visit).xss();
		BookMark.update({'sites._id':visit},{$inc:{'sites.$.Visits':1}},function(err, doc){
			if(err) console.log(err);
			// doc.sites.id(visit).update({$inc:{'Visits':1}});
			console.log(doc)
		});
	});
	app.get('/del/:siteid', function(req, res) {
		var siteid = sanitize(req.params.siteid).trim();
		siteid = sanitize(siteid).xss();
		BookMark.findOne({'sites._id':siteid},function(err, doc){
			if(err) return console.log(err);
			doc.sites.id(siteid).remove();
			doc.save(function(err){
				if(err) return res.send({type:'err',msg:'删除失败'});
				return res.send({type:'suc',msg:'删除成功'});
			})
		});
	});
	app.get('/manage', function(req, res){
		BookMark.find({}, function(err, doc){
			res.render('manage', {title:'管理', data: doc});
		})
	});
	app.get('/editsite/:siteid', function(req, res){
		var siteid = sanitize(req.params.siteid).trim();
		siteid = sanitize(siteid).xss();
		BookMark.findOne({'sites._id':siteid}, function(err, doc){
			if(err) console.log(err);
			if(doc){
				return res.send(doc.sites.id(siteid));
			} else {
				BookMark.findOne({'_id': siteid}, function(err, doc){
					if(err) console.log(err);
					if(doc){
						res.send({
							_id: doc._id,
							name: doc.classify,
							sorted: doc.sorted
						})
					}
				})
			}
		});
	});
	app.get('/api/:action/:par?', function(req, res) {
		if(req.params.action == 'annotate'){
			res.send("hi 1");
		} else {
			res.send('err');
		}
	});
}